﻿using Basic.WxModel.DB;
using Basic.WxModel.WxMer;
using Basic.WxRepository;
using WeDonekRpc.CacheClient.Interface;
using WeDonekRpc.Helper;
namespace Basic.WxCollect.lmpl
{
    internal class WxMerCollect : IWxMerCollect
    {
        private readonly IWxMerRepository _WxMer;
        private readonly ICacheController _Cache;
        public WxMerCollect (IWxMerRepository wxMer,
            ICacheController cache)
        {
            this._Cache = cache;
            this._WxMer = wxMer;
        }
        public DBWxMer Find (string appId)
        {
            return this._WxMer.FindWxMer(appId);
        }
        public long Add (WxMerAdd add)
        {
            DBWxMer mer = this._WxMer.Add(add);
            this._Clear(add.AppId);
            return mer.Id;
        }

        private void _Clear (string appId)
        {
            string key = "WxMerId_" + appId;
            _ = this._Cache.Remove(key);
        }
        public long GetWxMerId (string appId)
        {
            string key = "WxMerId_" + appId;
            if (!this._Cache.TryGet(key, out long id))
            {
                id = this._WxMer.FindWxMerId(appId);
                if (id == 0)
                {
                    _ = this._Cache.Add(key, id, new TimeSpan(0, 1, 0));
                }
                else
                {
                    _ = this._Cache.Add(key, id);
                }
            }
            if (id == 0)
            {
                throw new ErrorException("wx.mer.not.find");
            }
            return id;
        }

        public void Set (DBWxMer mer, WxMerSet set)
        {
            if (this._WxMer.Update(mer, set))
            {
                this._Clear(mer.AppId);
            }
        }

    }
}
